package com.ruge.sorm.util;

import com.ruge.sorm.bean.ColumnInfo;
import com.ruge.sorm.bean.JavaFieldGetSet;
import com.ruge.sorm.bean.TableInfo;
import com.ruge.sorm.core.DBManager;
import com.ruge.sorm.core.MysqlTypeConvertor;
import com.ruge.sorm.core.TableContext;
import com.ruge.sorm.core.TypeConvertor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 封装了生成Java文件（源代码）常用的操作
 *
 * @author admin
 * @version 2023/10/21 10:17
 **/
public class JavaFileUtils {
    /**
     * 根据字段信息生成Java属性信息。如：varchar username --> private String userName; 以及相应的get和set方法
     *
     * @param columnInfo 字段信息
     * @param convertor  类型转化器
     * @return Java属性和get、set方法
     */
    public static JavaFieldGetSet createFieldGetSetSRC(ColumnInfo columnInfo, TypeConvertor convertor) {

        JavaFieldGetSet jfs = new JavaFieldGetSet();

        String javaFieldType = convertor.databaseTypeToJavaType(columnInfo.getDataType());

        jfs.setFieldInfo("\tprivate " + javaFieldType + " " + columnInfo.getName() + ";\n");

        // public String getUsername(){return username;}
        StringBuilder getSrc = new StringBuilder();
        getSrc.append("\tpublic " + javaFieldType + " get" + StringUtils.firstCharToUpperCase(columnInfo.getName()) + "(){\n");
        getSrc.append("\t\treturn " + columnInfo.getName() + ";\n");
        getSrc.append("\t}\n");
        jfs.setGetInfo(getSrc.toString());

        // public void setUsername(String username){ this.username=username;}
        StringBuilder setSrc = new StringBuilder();
        setSrc.append("\tpublic void set" + StringUtils.firstCharToUpperCase(columnInfo.getName()) + "(");
        setSrc.append(javaFieldType + " " + columnInfo.getName() + ")" + "{\n");
        setSrc.append("\t\tthis." + columnInfo.getName() + " = " + columnInfo.getName() + ";\n");
        setSrc.append("\t}\n");
        jfs.setSetInfo(setSrc.toString());

        return jfs;
    }


    /**
     * 根据表信息生成Java类的源代码
     *
     * @param tableInfo 表信息
     * @param convertor 数据类型转化器
     * @return Java类的源代码
     */
    public static String createJavaSrc(TableInfo tableInfo, TypeConvertor convertor) {
        Map<String, ColumnInfo> columns = tableInfo.getColumns();
        List<JavaFieldGetSet> javaFields = new ArrayList<>();
        for (ColumnInfo c : columns.values()) {
            javaFields.add(createFieldGetSetSRC(c, convertor));
        }

        StringBuilder src = new StringBuilder();

        // 生成Package语句
        src.append("package " + DBManager.getConf().getPoPackage() + ";\n\n");

        // 生成import语句
        src.append("import java.sql.*;\n");
        src.append("import java.util.*;\n\n\n");

        // 生成类声明语句
        src.append("public class " + StringUtils.firstCharToUpperCase(tableInfo.getTname()) + " {\n\n");

        // 生成属性列表
        for (JavaFieldGetSet f : javaFields) {
            src.append(f.getFieldInfo());
        }
        src.append("\n\n");

        // 生成get方法列表
        for (JavaFieldGetSet f : javaFields) {
            src.append(f.getGetInfo());
        }

        // 生成set方法列表
        for (JavaFieldGetSet f : javaFields) {
            src.append(f.getSetInfo());
        }

        // 生成类结束
        src.append("}\n");

        return src.toString();
    }

    public static void createJavaPOFile(TableInfo tableInfo, TypeConvertor convertor) {
        String src = createJavaSrc(tableInfo, convertor);
        BufferedWriter bw = null;
        String srcPath = DBManager.getConf().getSrcPath() + "\\";
        String packagePath = DBManager.getConf().getPoPackage().replaceAll("\\.", "/");

        File f = new File(srcPath + packagePath);

        System.out.println(f.getAbsoluteFile() + "*************");

        if (!f.exists()) { // 如果指定目录不存在，则帮助用户建立
            f.mkdirs();
        }
        try {
            bw = new BufferedWriter(new FileWriter(f.getAbsoluteFile() + "/" + StringUtils.firstCharToUpperCase(tableInfo.getTname()) + ".java"));
            bw.write(src);
            System.out.println("建立表：" + tableInfo.getTname() + "对应的Java类：" + StringUtils.firstCharToUpperCase(tableInfo.getTname()) + ".java");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bw) {
                    bw.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
